package cc.linker.steplink.crm.merchant.service;

import cc.linker.steplink.crm.commons.service.CommonsService;
import cc.linker.steplink.crm.commons.utils.NumberUtils;
import cc.linker.steplink.crm.merchant.dao.acs.LinkAccountDao;
import cc.linker.steplink.crm.merchanth5.dao.MallBoomDao;
import cc.linker.steplink.crm.merchanth5.dao.acs.MerchantWalletDao;
import cc.linker.steplink.crm.merchanth5.service.acs.MerchantSalerService;
import cc.linker.steplink.crm.merchanth5.service.common.SmsService;
import cc.linker.steplink.crm.merchanth5.util.ParamSignUtils;
import cc.linker.steplink.crm.merchant.dao.MallBoomBackMapper;
import cc.linker.steplink.crm.merchant.dao.ShopGoodsMapper;
import cc.linker.steplink.crm.merchant.pojo.MallBoomPo;
import cc.linker.steplink.crm.response.GlobalException;
import cc.linker.steplink.crm.response.ResponseException;
import com.mongodb.util.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.NameValuePair;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class MallBoomBackService {

    @Autowired
    private MallBoomBackMapper mallBoomBackMapper;

    @Autowired
    private ShopGoodsMapper shopGoodsMapper;

    @Autowired
    private MallBoomDao mallBoomDao;

    @Autowired
    private SmsService smsService;

    @Autowired
    private MerchantWalletDao merchantWalletDao;

    @Autowired
    private MallBoomBackService mallBoomBackService;

    @Autowired
    private MerchantSalerService MerchantSalerService;

    @Autowired
    private CommonsService commonsService;

    @Value("${wcpay.smsurl}")
    private String smsurl;

    public MallBoomPo getSet(String orgId) {
        MallBoomPo result = mallBoomBackMapper.getSet(orgId);
        //如果是null 设置初始值
        if (null == result) {
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("orgId", orgId);
            params.put("freezeTime", 30);
            params.put("amount", 0);
            params.put("rebate", 0);
            params.put("recommend", 0);
            params.put("seniorAmount", 0);
            params.put("seniorRebate", 0);
            params.put("serviceRatio", 50);
            params.put("recommendRatio", 50);
            params.put("platformRatio", 0);
            params.put("originalRatio", 0);
            params.put("unhappen", 1);
            params.put("agentCheck", 0);
            params.put("promoterCheck", 0);
            params.put("salerPromoter", 0);
            mallBoomBackMapper.setMall(params);
            return mallBoomBackMapper.getSet(orgId);
        } else {
            return result;
        }
    }

    public int setMall(Map<String, Object> params) {
        return mallBoomBackMapper.setMall(params);
    }

    public List<Map<String, Object>> getSales(Map<String, Object> params) {
        String orgId = params.get("orgId").toString();
        Integer payMode = Integer.parseInt(params.get("payMode").toString());
        List<Map<String, Object>> list = mallBoomBackMapper.getSales2(params);
        list.forEach(x -> {
            if(StringUtils.isEmpty(x.get("customerName"))){
                if(!StringUtils.isEmpty(x.get("customerPhone"))){
                    String customerPhone = x.get("customerPhone").toString();
                    x.put("customerName","手机尾号"+customerPhone.substring(customerPhone.length()-4)+"用户");
                }
            }
            if (x.get("amount") != null) {
                x.put("amount", NumberUtils.fenToYuan(Long.parseLong(x.get("amount").toString())));
            }
        });
        return list;
    }

    public List<Map<String, String>> getSonBoomList(String orgId) {
        return mallBoomBackMapper.getSonBoomList(orgId);
    }

    public void updateGoodsMax(Map<String, Object> param) throws Exception {

        int i = mallBoomBackMapper.updateGoodsMax(param);
        if (i < 1) {
            throw new GlobalException(new ResponseException(400, "操作失败"));
        }
    }

    public void suspend(Map<String, Object> param) throws Exception {
        //修改状态
        param.put("goodsStatus", 0);
        int i = mallBoomBackMapper.changeStatus(param);
        if (i < 1) {
            throw new GlobalException(new ResponseException(400, "操作失败"));
        }
        //下架商品 该小b 用户下的所有商品
        shopGoodsMapper.updateStatusByBelongId(param);
    }

    public void recovery(Map<String, Object> param) throws Exception {
        param.put("goodsStatus", 1);
        Integer i = mallBoomBackMapper.changeStatus(param);
        if (i < 1) {
            throw new GlobalException(new ResponseException(400, "操作失败"));
        }
    }

    public Map<String, Object> getSalerVerify(String customerId) {
        return mallBoomBackMapper.getSalerVerify(customerId);
    }

    public List<Map<String, Object>> salerVerifyList(String orgId) {
        return mallBoomBackMapper.salerVerifyList(orgId);
    }

    public Map<String, Object> getSalerVerifyById(Integer id) {
        return mallBoomBackMapper.getSalerVerifyById(id);
    }

    public void doVerify(Map<String, Object> param) throws Exception {
        Integer status = Integer.parseInt(param.get("status").toString());
        String businessType = "";
        if (status == 1) {
            //认证失败
            param.put("authenticateState", 0);
            param.put("checkStatus", 1);
            param.put("checkRemark", "认证失败");
            param.put("goodsStatus", 0);
            businessType = "9002";
        } else if (status == 2) {
            //认证成功
            param.put("authenticateState", 1);
            param.put("checkStatus", 2);
            param.put("checkRemark", "认证成功");
            param.put("goodsStatus", 1);
            businessType = "9003";
        }
        //更新busi_merchant_saler
        Integer i = mallBoomBackMapper.changeAuthenticateStatus(param);
        if (i < 1) {
            throw GlobalException.build("操作失败");
        }
        //更新busi_merchant_saler_verify
        Integer n = mallBoomBackMapper.changeCheckStatus(param);
        if (n < 1) {
            throw GlobalException.build("操作失败");
        }

        //根据customerId 获取手机号
        String customerId = param.get("customerId").toString();
        String phone = mallBoomBackMapper.getPhoneByCustomerId(customerId);
        String orgId = merchantWalletDao.getOrgIdByCid(customerId);
        // 发送审核结果通知
//        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
//        nvps.add(new BasicNameValuePair("businessType", businessType));
//        nvps.add(new BasicNameValuePair("plantName", "STEPLINK"));
//        nvps.add(new BasicNameValuePair("mobilNumber", phone));
//        nvps.add(new BasicNameValuePair("params", null));
//        nvps.add(new BasicNameValuePair("token", null));
//
//        String result = ParamSignUtils.callService(smsurl + "/sms/sendVerificationCode", nvps, 0, 0);

        Map<String, Object> nvps = new HashMap<>();
        nvps.put("businessType", businessType);
        nvps.put("mobilNumber", phone);
        nvps.put("params", null);
        nvps.put("token", null);
        String result = smsService.sendVerification(orgId, nvps);

        Object parse = JSON.parse(result);
        Map ret = (Map) parse;
        if ((Integer) ret.get("rt") != 1) {
            //todo 记录短信发送失败日志
            LOGGER.error("MallBoomBackService_doVerify" + result);
        }
    }

    public List<Map<String, Object>> getUserList(Map<String, String> map) {
        return mallBoomBackMapper.getUserList(map);
    }

    public List<Map<String, Object>> getAllUserList(Map<String, String> map) {
        return mallBoomBackMapper.getAllUserList(map);
    }

    public List<Map<String, Object>> getParentList(Map<String, String> map) {
        return mallBoomBackMapper.getParentList(map);
    }

    public List<Map<String, Object>> getUserParentList(Map<String, String> map) {
        return mallBoomBackMapper.getUserParentList(map);
    }

    public Integer getSalerCount(Map map) {
        return mallBoomDao.getSalerCount(map);
    }

    public String getUserPushArticleIds(String orgId) {
        return mallBoomDao.getUserPushArticleIds(orgId);
    }

    public void updateSalerLabelAndRemark(Map<String, Object> map) {
        mallBoomDao.updateSalerLabelAndRemark(map);
    }


    public Map<String, String> getOrgAccountConf(String orgId, String status) {
        Map<String, String> accconf = mallBoomDao.getOrgAccountConf(orgId, status);
        if (null != accconf && StringUtils.isEmpty(accconf.get("changeTime"))) {
            accconf.put("changeTime", "");
        }
        return accconf;
    }

    public void addOrgAccountConf(String orgId, String status) {
        mallBoomDao.addOrgAccountConf(orgId, status);
    }

    public Boolean saveOrgAccountConf(Map param) {
        return mallBoomDao.saveOrgAccountConf(param);
    }

    public List<Map<String, String>> getAllOrgConf() {
        return mallBoomDao.getAllOrgConf();
    }

    public void setOrgAccountConf(Map param) {
        mallBoomDao.setOrgAccountConf(param);
    }

    public Boolean cancelOrgAccountConf(String orgId) {
        return mallBoomDao.cancelOrgAccountConf(orgId);
    }

    public List<Map<String, Object>> getProUserList(Map<String, String> param) {
        String user = param.get("user");
        String parent = param.get("parent");
        List<Map<String, Object>> allUserList;
        if (!"".equals(user) && "".equals(parent)) {
            //只搜用户
            param.put("user", user);
            allUserList = mallBoomBackService.getUserList(param);
        }else if ("".equals(user) && !"".equals(parent)) {
            //只搜上级
            parent = "平台".equals(parent)?"-1":parent;
            param.put("parent", parent);
            allUserList = mallBoomBackService.getParentList(param);
        }else if (!"".equals(user)) {
            //同时搜索
            parent = "平台".equals(parent)?"-1":parent;
            param.put("parent", parent);
            param.put("user", user);
            allUserList = mallBoomBackService.getUserParentList(param);
        }else{
            allUserList = mallBoomBackService.getAllUserList(param);
        }
        for (Map<String, Object> item : allUserList) {
            if(StringUtils.isEmpty(item.get("cName"))){
                if(!StringUtils.isEmpty(item.get("cPhone"))){
                    String cPhone = item.get("cPhone").toString();
                    item.put("cName","手机尾号"+cPhone.substring(cPhone.length()-4)+"用户");
                }
            }
            if (null == item.get("pName") && (null == item.get("pPhone") || "".equals(item.get("pPhone")))) {
                item.put("pName", "平台");
                item.put("pPhone", "-");
            }
            if (null == item.get("saveTime")) {
                item.put("saveTime", "-");
            }else{
                item.put("saveTime",item.get("saveTime").toString().substring(0,19));
            }
            Map<String, String> salerParam = new HashMap<String, String>();
            salerParam.put("orgId", item.get("corgId").toString());
            salerParam.put("customerId", item.get("ccustomerId").toString());
            Integer salerCount = mallBoomBackService.getSalerCount(salerParam);
            //联盟商家-》推广员-》加盟代理
            String cUserType = "";

            Integer agentCount = MerchantSalerService.getcAgentCount(item.get("ccustomerId").toString(), item.get("corgId").toString());

            if (salerCount > 0) {//判断联盟商家
                cUserType = cUserType + ",联盟商家";
            }
            if ("promoter".equals(item.get("cUserType"))) {//判断加盟代理
                cUserType = cUserType + ",加盟代理";
            }
            if (agentCount > 0) {//判断推广员
                cUserType = cUserType + ",推广员";
            }
            if ("".equals(cUserType)) {
                cUserType = "普通用户";
            }
            if (cUserType.startsWith(",")) {
                cUserType = cUserType.substring(1);
            }
            item.put("cUserType", cUserType);
        }
        return allUserList;
    }

    public void exportGetuserlist(Map<String, String> param, HttpServletResponse response) throws Exception {
        String[] title = {"昵称", "手机号", "用户类型", "上级昵称", "上级手机号", "关联时间"};
        String fileName = "";
        if(StringUtils.isEmpty(param.get("startTime")) || StringUtils.isEmpty(param.get("endTime"))){
            fileName = "客户关系";
        }else{
            fileName = "客户关系（"+param.get("startTime").substring(0,10)+"-"+param.get("endTime").substring(0,10)+")";
        }
        String[] strings = {"cName", "cPhone", "cUserType", "pName", "pPhone", "saveTime"};
        List<Map<String, Object>> list = getProUserList(param);
        commonsService.excelDownload(list, strings, title, fileName, response);
    }
}
